<?php

declare(strict_types=1);

namespace app\admin\service;

use app\admin\model\LogisticsOrder as LogisticsOrderModel;
use app\admin\common\ServiceResponse;
use app\common\service\Mail;
use app\common\shopify\FulfillmentService;
use think\facade\Db;
use think\facade\Log;

class LogisticsOrder
{

    use ServiceResponse;

    protected $model;

    public function __construct()
    {
        $this->model = new LogisticsOrderModel();
    }

    public function update($params)
    {

        $res = $this->model->where('id', $params['id'])->find();
        $old_logistics_no = $res->logistics_no;

        if (!$res) {
            return ['code' => 400000, 'message' => '未找到相关数据'];
        }
        foreach ($params as $key => $value) {
            if ('logistics_voucher' == $key) {
                $value = implode(',', $value);
            }
            if ('cost' == $key) {
                $value = json_encode( $value);
            }
            if ($res->$key != $value) {
                $res->$key = $value;
            }
        }
        $new_logistics_no = $res->logistics_no;
        $orderId = Db::name('logistics_order_item')->where('logistics_order_id', $res->id)->value('order_id');
        $orderInfo = Db::name('order')->where('id', $orderId)->find();
        if ($new_logistics_no && $old_logistics_no != $new_logistics_no) {

            $mailService = new Mail();
            $mailService->send('order_shipped', [
                'logistics' => $res->toArray(),
                'order_info' => $orderInfo
            ]);
        }

        $result = $res->save();

        if ($result) {
            try {
                #shopify 订单 发货通知
                if ($orderInfo['source'] == 2 && $res->logistics_no) {
                    $params['logistics_order'] = $params['id'];
                    $params['type'] = 'update';
                    $params['order_id'] = $orderId;
                    $shopify = New FulfillmentService();
                    $shopify->createOrUpdateFulfillment($params);
                }
            } catch (\Exception $e) {

                Log::error('修改物流单通知shopify失败 ：' . $e->getMessage());

            }
            return $this->success();
        } else {
            return $this->error(1, '操作失败');
        }
    }
}
